package com.vf.s.mvc.biz.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.vf.core.controller.BaseController;
import com.vf.core.model.ImportModel;
import com.vf.core.render.HttpClientResult;
import com.vf.core.util.HttpUtil;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.biz.BizVideo;
import com.vf.s.common.model.biz.VideoClassify;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.mvc.biz.service.BizVideoService;
import com.vf.s.mvc.biz.service.ReadVideoService;

public class BizVideoContoller  extends BaseController{

	@Inject
	private BizVideoService srv;
	ExecutorService executor = Executors.newFixedThreadPool(20);
	
	public void index() {
		List<Record> fieldList = Db.find("SELECT column_name value,case when column_comment !='' then column_comment else column_name end name "
				+ " FROM information_schema.COLUMNS WHERE table_name = ?",BizVideo.TABLE_NAME);
	    setAttr("fieldList", fieldList);
		render("list.html");
	}
	
	public void selectList() {
		set("sceneId", getPara("sceneId"));
		set("targetId", getPara("targetId"));
		render("selectList.html");
	}
	
	public void edit() {
		set("objId", getPara("objId"));
		set("sceneId", getPara("sceneId"));
		set("event", getPara("event"));
		BizVideo bizVideo=BizVideo.dao.findById(getPara("id"));
		set("bizVideo", bizVideo);
		render("edit.html");
	}
	
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String classifyId = getPara("classifyId");
		String objId = getPara("objId");
		
		String sqlExceptSelect = " FROM " + BizVideo.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%' OR  O.CODE LIKE '%" + keyword + "%' ) ";
		}
		if (!StrKit.isBlank(classifyId)) {
			sqlExceptSelect += " AND classifyId='"+classifyId+"' ";
		}
		if (!StrKit.isBlank(objId)) {
			sqlExceptSelect += " AND objId='"+objId+"' ";
		}
		sqlExceptSelect += "  ORDER BY   O.CREATETIME DESC ";
		Page<BizVideo> page = BizVideo.dao.paginate(pageNumber, pageSize, "select o.*,(select NAME from "+VideoClassify.TABLE_NAME+" where id=o.classifyId) classifyName ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	/***
	 * 保存
	 */
	public void save() {
		BizVideo model = getModel(BizVideo.class);
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			model.setCreateUserId(ShiroKit.getLoginUser().getId());
			model.setCreateUserName(ShiroKit.getLoginUser().getName());
			if (model.save()) {
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	/***
	 * 删除
	 * 
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		BizVideo model = BizVideo.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	
	
	public void editor() {
		String id = getPara("id");
		this.setAttr("id", id);
		render("editor.html");
	}

	public void getInfoPage() {
		String id = getPara("sceneId");
		this.setAttr("id", id);
		render("info.html");
	}
	
	public void findById() throws Exception {
		String id = getPara("id");
		BizVideo model = BizVideo.dao.findById(id);
		if (model != null) {
			renderSuccess("成功！",model);
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void updataSynStatus() throws Exception {
		String id = getPara("id");
		String status = getPara("status");
		BizVideo model = BizVideo.dao.findById(id);
		if (model != null) {
			model.setSynStatus(status);
			if(model.update()) {
				renderSuccess("更新成功！",model);
			}else {
				renderSuccess("更新失败！",model);
			}
			
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void listDataAll() {
		List<BizVideo> lists = BizVideo.dao.find("select * from "+BizVideo.TABLE_NAME+" where synStatus='0' ");
		if(lists!=null && lists.size()>0) {
			renderSuccess("成功！", lists);
		}else {
			renderError("无数据！");
		}
	}
	
	//excel从模板文件导入 2021-01-20
	public void execlImport() throws Exception {
		UploadFile uploadFile = getFile();
		ReadVideoService rv = new ReadVideoService(uploadFile.getFile().getPath());
		String err= rv.Read();
		if(err!=null && err.length()>0)
			renderError(err);
		else
		{
			List<BizVideo> list= rv.list;
			for(BizVideo bizVideo: list) {
				bizVideo.setId(UuidUtil.getUUID());
				bizVideo.save();
			}
			renderSuccess("导入成功，共导入"+list.size()+"条数据!");
		}
	}
	
	//视频同步，2021-01-20
	public void synVideoFromRTC() {
		String str = srv.synVideoFromRTC();
		if(str==null || str.length()==0)
			renderSuccess("同步成功");
		else
			renderError(str);
	}
	//视频推送，2021-01-20
	public void synVideoToRTC() {
		String str = srv.synVideoToRTC();
		if(str==null || str.length()==0)
			renderSuccess("同步成功");
		else
			renderError(str);
	}
		

	@SuppressWarnings("resource")
	public void deviceImport() throws Exception {
		UploadFile uploadFile = getFile();
		Workbook workbook = null;
		ImportModel importModel = new ImportModel();
		// 读取目标文件
		File excelFile = new File(uploadFile.getFile().getPath());
		InputStream is = new FileInputStream(excelFile);
		// 判断文件是xlsx还是xls
		if (excelFile.getName().endsWith("xlsx")) {
			workbook = new XSSFWorkbook(is);
		} else {
			workbook = new HSSFWorkbook(is);
		}
		List<Map<String, String>> sheets = null;
		Map<String, List<Map<String, String>>> fields = null;
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
			Sheet sheet = workbook.getSheetAt(numSheet);
			if (sheet == null) {
				continue;
			}
			if(sheets==null)sheets=new ArrayList<Map<String, String>>();
			if(fields==null)fields=new HashMap<String, List<Map<String, String>>>();
			String sheetName = workbook.getSheetName(numSheet);
			Map<String, String> sheetMap = new HashMap<String, String>();
			sheetMap.put("sheetName",sheetName);
			
			Row fRow = sheet.getRow(0);
			List<Map<String, String>> fieldList = new ArrayList<Map<String,String>>();
			for (Cell cell : fRow) {
				Map<String, String> fieldMap = new HashMap<String, String>();
				fieldMap.put("fieldName", cell.getStringCellValue());
				fieldList.add(fieldMap);
			}
			sheets.add(sheetMap);
			fields.put(sheetName, fieldList);
		}
		importModel.setSheets(sheets);		
		importModel.setFields(fields);
		importModel.setFilePath(uploadFile.getFile().getPath());
		renderSuccess("成功！",importModel);
	}

	public void importAction() throws IOException {
		Workbook workbook = null;
		String path = getPara("path");
		String data = getPara("data");
		String sheetName=getPara("sheetName");
		String classifyId = getPara("classifyId");
		Map<Integer, String> mapKey = new HashMap<Integer, String>();    
		if(StrKit.isBlank(data)) {
			renderError("无效的参数！");
			return;
		}
		InputStream is  = null;
		try {
			JSONObject json = JSONObject.parseObject(data);
			File excelFile = new File(path);
			// 读取目标文件
			is = new FileInputStream(excelFile);
			// 判断文件是xlsx还是xls
			if (excelFile.getName().endsWith("xlsx")) {
				workbook = new XSSFWorkbook(is);
			} else {
				workbook = new HSSFWorkbook(is);
			}
			Sheet sheet = workbook.getSheet(sheetName);
			if (sheet == null) {
				renderError("sheet为空！");
				return;
			}
			int unmber= 0;
			for (int i=0;i<sheet.getLastRowNum();i++) {
				Row row = sheet.getRow(i);
				if(i==0) {
					for (Cell cell : row) {
						for(String k : json.keySet()){    
							if(StrKit.equals(cell.getStringCellValue(), k)) {
								mapKey.put(cell.getColumnIndex(), json.getString(k));
							}
			            }   
					}
				}else {
					BizVideo bizVideo= new BizVideo();
					bizVideo.setId(UuidUtil.getUUID());
					for (Cell cell : row) {
						bizVideo.setClassifyId(classifyId);
						if(!StrKit.isBlank(cell.getStringCellValue()) && !StrKit.isBlank(mapKey.get(cell.getColumnIndex()))) {
							bizVideo.set(mapKey.get(cell.getColumnIndex()), cell.getStringCellValue());
						}
					}
					if(bizVideo.save()) {
						unmber++;
					}
				}
			}
			renderSuccess("成功导入【"+unmber+"】条数据！");
		} catch (Exception e) {
			renderError("导入失败！异常【"+e.getMessage()+"】。");
			e.printStackTrace();
		}finally {
			if(is!=null)is.close();
		}
	}
	
	 
	/**
	 * 同步视频
	 * @return
	 */
	@Before(Tx.class)
	public void synCameraFromRTC() {
		String rtcKey = getPara("rtcKey");
		String sceneId = getPara("sceneId");
		String rtcSerUrl=PropKit.use("app-config-dev.txt").get(rtcKey);
		renderSuccess("数据异步处理中！！！");
	    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
	        @Override
	        public Integer get() {
	            try {
	            	//添加图层
	    			HttpClientResult result = HttpUtil.doGet(rtcSerUrl + "/api/getMediaGroupList", null, null);
	    			if (result.getCode() == 200) {
	    				if (!StrKit.isBlank(result.getContent())) {
	    					JSONArray srmResult = JSONArray.parseArray(result.getContent());
	    					if(!srmResult.isEmpty()) {
	    						for (Object object : srmResult) {
	    							JSONObject cObj = (JSONObject) object;
	    							srv.saveOrUpdateBizLayer(cObj, sceneId,cObj.getString("parentId"));
	    						}
	    					}
	    				}
	    			}
	            } catch (Exception e) {
	            	e.printStackTrace();
	            }
	            return 3;
	        }
	    }, executor);
	    future.thenAccept(e -> System.out.println(e));
		
	    CompletableFuture<Integer> futureList = CompletableFuture.supplyAsync(new Supplier<Integer>() {
	        @Override
	        public Integer get() {
	            try {
	            	//添加点
					HttpClientResult resultVideo = HttpUtil.doGet(rtcSerUrl + "/api/getMediaList", null, null);
					if (resultVideo.getCode() == 200) {
						if (!StrKit.isBlank(resultVideo.getContent())) {
							JSONArray srmResultList = JSONArray.parseArray(resultVideo.getContent());
							if(!srmResultList.isEmpty()) {
								for (Object object : srmResultList) {
									JSONObject cObj = (JSONObject) object;
									//添加图层
									srv.saveOrUpdateBizLayer(cObj, sceneId,cObj.getString("id"));
									//添加点
									srv.saveOrUpdateBizPoint(cObj, sceneId);
									//添加视频
									srv.saveOrUpdateBizVideo(cObj);
								}
							}
						}
					}
	            } catch (Exception e) {
	            	e.printStackTrace();
	            }
	            return 3;
	        }
	    }, executor);
	    futureList.thenAccept(e -> System.out.println(e));
	}
}
